<?php

define("nl", "<br />");

require 'includes/setUp.php';  

/*** Menu ***/
$notifCount = 4;

if (!$LOGGED) {
  $menuInput = array("view.php" => T_("View"),
                   //"favorites.php" => T_("Favorites"),
                   //"settings.php" => "Settings",
                  // "login.php" => T_("Login")
                );
}
else {
  $menuInput = array("notification.php" => '<img src="'.WebRoot.'themes/'.$theme.'/images/notification.png" alt="" title="" />'.(($notifCount > 0) ? '<span class="notification-number">'.$notifCount.'</span>' : ''), 
                     "view.php" => T_("View"),
                     "favorites.php" => T_("Favorites"),
                     "myalbums.php" => T_("My Album"),
                     "settings.php" => T_("Settings"),
                     "controllers/logout.php" => T_("Logout"));                   
}

$menuActive = basename($_SERVER["REQUEST_URI"]);
if (strpos($menuActive, "?") !== false ) {
  $menuActive = substr($menuActive, 0, strpos($menuActive, "?"));
}

ob_start();
include './includes/Views/head.php';
if(isset($_GET['errMsg'])) Messages::errorMessage(rawurldecode($_GET['errMsg']));

/*** Show correct page ***/
switch ($page) {

   case "login": 
     if (isset ($_POST["login"]["logOn"])){
       try {

         $auth->logIn($_POST["login"]["name"], 
                      $_POST["login"]["password"], 
                      isset($_POST["login"]["remember"])? Authentication::PERMANENT_LOGIN : Authentication::TEMPORARY_LOGIN);                 
         globalFunc::redirect();

       } catch (AuthException $ex) {
         Messages::errorMessage($ex->getMessage());
         unset($_POST);
       }

     }
     break;

   case "index":
     echo '<h2>'.T_('Latest Albums').'</h2>';
     break;

   case "forgottenPassword": 
     if (isset($_POST["forgotten"]["submit"])) {
       try {
         $auth->recoveryRequest($_POST["forgotten"]["email"]);
         echo T_('Recovery url was sent to the entered e-mail. Please follow instructions within');
       } catch (AuthException $ex) {
         Messages::errorMessage($ex->getMessage());
       } catch (Exception $ex) {
         globalFunc::redirect(WebRoot.'500.php');
       }
     }
     include "includes/views/forgottenPassword.php";
     break; 
   
   case "recover":
     try {      
       $generatedPass = $auth->recoverAccount($_GET['user'], $_GET['token']);       
       include 'includes/views/changePass.php';
       
       
     } catch (AuthException $ex) {
       Messages::errorMessage($ex->getMessage());
     }
     break;
   
   case "editAlbum":
     
     if (!$LOGGED) {
       Messages::errorMessage (T_('You have to be logged on'));
       break;
     }  
     
     if (isset ($_GET['album']) && is_numeric($_GET["album"])) {
       $editAlbum = $db->find('Album', $_GET['album']);
     }
     include 'includes/Views/editAlbum.php';
     break;
   
   case "album":      
     
     $id = (isset($_GET["idAlbum"]) && is_numeric($_GET["idAlbum"])) ? $_GET["idAlbum"] : null;
     $requiredAlbum = $db->find('Album', $id);
     
     if ($requiredAlbum == null) {
       Messages::errorMessage(T_('Album doesn\'t exists'));
       break;
     }        
     
     $isOwner = $LOGGED && ($requiredAlbum->User == $user);
     

/* Checking album password */
     if($requiredAlbum->ProtectionName == 'password' && !$isOwner) {
       
       if (isset($_SESSION['albums'][$requiredAlbum->idAlbum]) && $_SESSION['albums'][$requiredAlbum->idAlbum] == $requiredAlbum->Password) {         
         
       } elseif(isset($_POST['view']['password'])) {
         if (globalFunc::hashPassword($_POST['view']['password']) == $requiredAlbum->Password) {
           $_SESSION['albums'][$requiredAlbum->idAlbum] = globalFunc::hashPassword($_POST['view']['password']);
         }
         else {
           Messages::errorMessage(T_('Wrong password'));
           break;
         }
       } else {
         echo '<form action="'.WebRoot.'album.php?idAlbum='.$requiredAlbum->idAlbum.'" method="post">';
         echo '<input type="password" name="view[password]" />';
         echo '<input type="submit" name="view[submit]" value="'.T_('OK').'" />';  
         echo '</form>';
         break;
       }
     }
         

/* Is Logged, Is Owner */     
     if ($isOwner) {
       $albums = $db->getRepository('Album')->getAllAlbums($id);
     }

/* Is Logged, Is Not Owner */     
     if ($LOGGED && !$isOwner) {
       if($requiredAlbum->ProtectionName == 'private' && !$requiredAlbum->AllowedUsers->contains($user)) {
         Messages::errorMessage(T_('You are not authorized to view this album'));
         break;
       }
       
       $AlbumInFavoriteLink = ($user->FavoritesAlbums->contains($requiredAlbum)) ? 'remove' : 'add';
       $AlbumInFavoriteText = ($user->FavoritesAlbums->contains($requiredAlbum)) ? T_('Remove album from favorites') : T_('Add album to favorites');
       
       $UserInFavoriteLink = ($user->FavoritesUsers->contains($requiredAlbum->User)) ? 'remove' : 'add';
       $UserInFavoriteText = ($user->FavoritesUsers->contains($requiredAlbum->User)) ? T_('Remove user from favorites') : T_('Add user to favorites');
       
       $albums = $db->getRepository('Album')->getAccessibleAlbums($user, $requiredAlbum);
     }

/* Is Not logged */     
     if (!$LOGGED) {
       if (($requiredAlbum->ProtectionName == 'private') || ($requiredAlbum->ProtectionName == 'protected')) {
         Messages::errorMessage(T_('You are not authorized to view this album'));
         break;
       }
       $albums = $db->getRepository('Album')->getFreeAlbums($id);
     }
     
/* Breadcrumb navigation */
     $alb = $requiredAlbum;
     $breadCrumbNav = array();
     while (($alb = $alb->ParentAlbum) != null) {
       $breadCrumbNav[$alb->idAlbum] = $alb->Name;       
     }
     $breadCrumbNav = @array_reverse($breadCrumbNav, true);
     
     
     include 'includes/Views/albumMenu.php';

/* List of sub-albums */     
     echo '<div class="albums"><h2>'.T_('Albums').'</h2>';
     
     foreach($albums as $album) {       
       include 'includes/Views/albumList.php';
     }
     
     echo '</div>';
     echo '<div style="clear:both"></div>';
     
/* List of photos */     
     echo '<div class="photos"><h2>'.T_('Photos').'</h2>';
     
     foreach ($requiredAlbum->Photos as $photo) {       
       include 'includes/Views/photoList.php';
     }
     
     echo '</div>';
     echo '<div style="clear:both"></div>';
     
     
     break;
          
   case "register":
     
     if (isset($_POST["register"])) {
       try {
         $auth->registerAccount($_POST['register']['email'], $_POST['register']['password'], $_POST['register']['dname']);
       } catch (AuthException $ex) {
         Messages::errorMessage($ex->getMessage());
         include ('includes/Views/register.php');
       } catch (Exception $ex) {
         globalFunc::redirect(WebRoot.'500.php');
       }  
     } else {
       include ('includes/Views/register.php');
     }
     
     
     break;
       
   case "settings": 
     
     if (!$LOGGED) {
       Messages::errorMessage (T_('You have to be logged on'));
       break;
     }
     
     if (isset($_POST['password'])) {
       try {
         $auth->changePassword($_POST['password']['OldPassword'], $_POST['password']['RepeatPassword'], $_POST['password']['NewPassword'], $user);
         Messages::stateMessage(T_('Your password has been changed'));
       } catch (AuthException $ex) {
         Messages::errorMessage($ex->getMessage());
       }  
     }
     
     if (isset($_POST['personal'])) {
       try {
        //$user = new User();
         if (!empty($_POST['personal']['displayName']) && ($user->UserName != $_POST['personal']['displayName'])) {
           $checkUser = $db->getRepository('User')->findOneByUserName($_POST['personal']['displayName']);
           if ($checkUser != null) throw new Exception('User with that username already exists');
         }
         
         $user->UserName  = (empty($_POST['personal']['displayName'])) ? $user->UserName : $_POST['personal']['displayName'] ;
         $user->FirstName = (empty($_POST['personal']['firstName'])) ? null : $_POST['personal']['firstName'];
         $user->LastName  = (empty($_POST['personal']['lastName'])) ? null : $_POST['personal']['lastName'];
         $user->ICQ       = (empty($_POST['personal']['icq'])) ? null : $_POST['personal']['icq'];
         $user->Jabber    = (empty($_POST['personal']['jabber'])) ? null : $_POST['personal']['jabber'];
         $user->WebPage   = (empty($_POST['personal']['url'])) ? null : $_POST['personal']['url'];
         $user->Gender    = ($_POST['personal']['gender'] == 'male') ? 'male' : ($_POST['personal']['gender'] == 'female') ? 'female' : null;
         $user->Details   = (empty($_POST['personal']['details'])) ? null : $_POST['personal']['details'];

         if (!empty($_FILES['avatar']['tmp_name'])) {
           $image = new Image($_FILES['avatar']['tmp_name']);
           $image->resizeImage(200);
           $image->saveImage(User::PATH);

           //if ($user->AvatarUNC != null) @unset($_SERVER["DOCUMENT_ROOT"].WebRoot.);

           $user->AvatarUNC = $image->OutputFile;
           /** TODO: DELETE Old avatar */
           $image->dispose();
         }
         //$user-> = $_POST['personal'][''];
         
         $db->flush();
         Messages::stateMessage(T_('Your settings have been updated'));
       } catch(Exception $ex) {
         Messages::errorMessage($ex->getMessage());
       }       
     }
     include('includes/Views/settings.php');
     break;
      
   case "profile":
     if (!$LOGGED) {
       Messages::errorMessage (T_('You have to be logged on'));
       break;
     }
     
     $id = (isset($_GET["id"]) && is_numeric($_GET["id"])) ? $_GET["id"] : null;
      //$requiredAlbum = new Album();
     $requiredUser = $db->find('User', $id);
     
     if ($requiredUser == null) {
       Messages::errorMessage(T_('User doesn\'t exists'));
       break;
     }
     
     if (!$LOGGED) {
       Messages::errorMessage(T_('You have to be logged to view this page'));
       break;
     }
     
     
     $query = $db->createQuery('SELECT Count(a.idAlbum) as calbs, Sum(a.photoCount) as cphots FROM Album a JOIN a.user u WHERE u.idUser = ?1');
     $query->setParameter(1, $requiredUser->idUser);
     $res = $query->getSingleResult();
     $albumCount = $res['calbs'];
     $photoCount = $res['cphots'];
     
          
     
     include('includes/Views/profile.php');
     
     break;
     
   case "search":
     if (!isset($_GET['q']) || empty($_GET['q']) || strlen($_GET['q']) < 3 ) {
       Messages::errorMessage(T_('You have to enter at least 3 characters'));
       break;
     }
     
     
     
     break;

   case "view": 
     break;

   case "favorites": 
     if (!$LOGGED) {
       Messages::errorMessage (T_('You have to be logged on'));
       break;
     }
     
     include('includes/Views/favorites.php');
     
     break;
   
   case "userAlbums": 
     
     $id = (isset($_GET["idUser"]) && is_numeric($_GET["idUser"])) ? $_GET["idUser"] : null;
     $isOwner = $LOGGED && ($user->idUser == $id);
     
/* Required == logged */    
     if($isOwner)       
       globalFunc::redirect(WebRoot.'myalbums.php');

/* Logged */
     if($LOGGED && !$isOwner)
       $albums = $db->getRepository('Album')->getAccessibleAlbumsByUser($id, $user);
     
/* Unlogged */     
     if(!$LOGGED)
       $albums = $db->getRepository('Album')->getFreeAlbumsByUser($id);
     /*
     $qb = $db->createQuery('SELECT a FROM Album a WHERE a.idUser = ?1 AND a.parentAlbum IS NULL');
     $qb->setParameter(1, $id);
     //$albums = $db->getRepository('Album')->findBy(array('idUser' => $user->idUser, 'parentAlbum' => null));     
     $albums = $qb->getResult();*/
     $reqUser =  $db->find('User', $id);
     echo '<h2>'.T_('Albums of ').'<a href="'.WebRoot.'profile.php?id='.$id.'">'.$reqUser->UserName.'</a></h2>';
     
     foreach ($albums as $album) {
       if (!$LOGGED) {
         if ($albums->ProtectionName == "private" || $albums->ProtectionName == "protected") {
           continue;
         }
      } else {
        if ($album->ProtectionName == "private" && !$album->AllowedUsers->contains($user)) {
          continue;
        }
      }       
       include 'includes/Views/albumList.php';
     }     
     
     
     
     break;
   
   case "myalbums":           
          
     if (!$LOGGED) {
       Messages::errorMessage('You have to be logged on');
       break;
     }
     $isOwner = true;
     include 'includes/Views/albumMenu.php';
     
     $albums = $db->getRepository('Album')->getAllAlbumsByUser($user->idUser);
     
     echo '<h2>'.T_('My Albums').'</h2>';
     
     foreach ($albums as $album) {
       include 'includes/Views/albumList.php';
     }     
     
     break;

   case "notifications":
     if (!$LOGGED) {
       Messages::errorMessage (T_('You have to be logged on'));
       break;
     }
     
     try {
       
     } catch (Exception $ex) {
       
     }
     
   case "activate":
     try {
       $auth->activateAccount($_GET["user"], $_GET["token"]);
       echo T_('User succesfully activated. Now you can log in');
     } catch (AuthException $ex) {
       Messages::errorMessage($ex->getMessage());
     }  catch (Exception $ex) {
       echo $ex->getTraceAsString();
       globalFunc::redirect(WebRoot.'500.php');
     }
     break;

   default:
     globalFunc::redirect(WebRoot.'index.php');
     break;
}

  include 'includes/Views/tail.php';
  
  ob_end_flush();

?>
